import Mock from 'mockjs'
import _ from 'lodash'

const Random = Mock.Random.extend({
  phone: function () {
    const constellations = ['xiaomi', 'huawei', 'iphone', 'oppo', 'vivo', 'oneplus', 'realme', 'meizu', 'samsung', 'sony']
    return this.pick(constellations)
  }
})

const productList = (function () {
  const list = []

  for (let i = 0; i < Random.integer(10, 50); i++) {
    list.push({
      id: Random.guid(),
      name: Random.phone().toUpperCase() + ' ' + Random.integer(100, 500),
      desc: Random.csentence(),
      price: Random.integer(1000, 5000),
      inventory: Random.integer(10, 50),
      image: Random.image('100x100'),
      imageLarge: Random.image('300x300')
    })
  }
  return list
})()

function searchProduct (search) {
  return _.filter(productList, (prod) => {
    return prod.name.toLowerCase().match(search.toLowerCase()) !== null
  })
}

const getProductByPage = (params) => {
  let innerProductList = []

  if (params.search) {
    innerProductList = searchProduct(params.search)
  } else {
    innerProductList = productList
  }

  const [index, size, total] = [params.page || 1, params.size || 10, innerProductList.length]
  const len = total / size
  const totalPages = len - parseInt(len) > 0 ? parseInt(len) + 1 : len
  const newProductList = innerProductList.slice((index - 1) * size, index * size)

  return {
    page: index,
    size: size,
    list: newProductList,
    total: total,
    totalPages: totalPages
  }
}

const query = (id) => {
  const prod = _.find(productList, (product) => {
    return product.id === id
  })

  return prod || null
}

export default {
  query,
  getProductByPage
}
